import React, { useState, useRef, useEffect } from 'react';
import { Button, List, Tag } from 'antd';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';

// 父组件：多窗口通信管理
const OpenMultipleCommunicatingTabs = () => {
  const [windowMap, setWindowMap] = useState(new Map());
  const [windowList, setWindowList] = useState([]);
  const nextWindowId = useRef(1);
  const history = useHistory();

  // 打开新的子窗口
  const openNewTab = () => {
    const windowId = nextWindowId.current++;
    const newWindow = window.open('http://localhost:3001/#/admin/communicate-tab-multi', '_blank');

    // 数据传输的格式要相应更改
    // const url = history.createHref({ pathname: "/admin/communicate-tab-multi" }); // 生成完整 URL
    // const newWindow = window.open(url, "_blank", "noopener,noreferrer"); 
    // const newWindow = window.open('/communicate-tab', '_blank');
    
    if (newWindow) {
      // 存储窗口实例和状态
      setWindowMap(prevMap => {
        const newMap = new Map(prevMap);
        newMap.set(windowId, {
          window: newWindow,
          active: true,
          initializing: true, // 初始化中状态
          createdTime: new Date()
        });
        return newMap;
      });
      
      // 更新窗口列表
      setWindowList(prevList => [
        ...prevList,
        { id: windowId, status: '初始化中', created: new Date() }
      ]);
      
      // 发送初始化数据（携带窗口ID）
      setTimeout(() => { // 延迟发送，等待子窗口加载
        newWindow.postMessage(
          { 
            type: 'INIT_WINDOW', 
            data: { windowId, timestamp: new Date().getTime(), message: `来自父窗口的初始化数据 (窗口ID: ${windowId})`, }
          },
          '*'
        );
      }, 300);
    }
  };

  // 向指定窗口发送消息
  const sendToWindow = (windowId, message) => {
    const windowEntry = windowMap.get(windowId);
    if (windowEntry && windowEntry.active && !windowEntry.window.closed) {
      windowEntry.window.postMessage(
        { 
          type: 'PARENT_COMMAND', 
          data: { command: message, windowId } 
        },
        '*'
      );
    }
  };

  // 接收子窗口消息
  useEffect(() => {
    const handleMessage = (e) => {
      const { type, data } = e.data;
      const { windowId } = data || {};
      
      if (type === 'CHILD_INITIALIZED' && windowId !== undefined) {
        // 子窗口初始化完成
        setWindowMap(prevMap => {
          const newMap = new Map(prevMap);
          const windowEntry = newMap.get(windowId);
          if (windowEntry) {
            newMap.set(windowId, {
              ...windowEntry,
              active: true,
              initializing: false,
              initializedTime: new Date()
            });
          }
          return newMap;
        });
        
        // 更新窗口列表状态
        setWindowList(prevList => 
          prevList.map(item => 
            item.id === windowId ? { ...item, status: '活跃' } : item
          )
        );
        console.log(`子窗口 ${windowId} 初始化完成`);
      } else if (type === 'CHILD_RESPONSE' && windowId !== undefined) {
        console.log(`子窗口 ${windowId} 响应:`, data.payload);
      } else if (type === 'CHILD_CLOSED' && windowId !== undefined) {
        // 子窗口主动通知关闭
        handleChildClosed(windowId);
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [windowMap]);

  // 处理子窗口关闭
  const handleChildClosed = (windowId) => {
    setWindowMap(prevMap => {
      const newMap = new Map(prevMap);
      const windowEntry = newMap.get(windowId);
      if (windowEntry) {
        newMap.set(windowId, {
          ...windowEntry,
          active: false,
          closedTime: new Date()
        });
      }
      return newMap;
    });
    
    setWindowList(prevList => 
      prevList.map(item => 
        item.id === windowId ? { ...item, status: '已关闭' } : item
      )
    );
  };

  // 检测窗口是否关闭（备用方案）
  useEffect(() => {
    const checkWindows = () => {
      setWindowMap(prevMap => {
        const newMap = new Map(prevMap);
        newMap.forEach((entry, id) => {
          if (entry.active && entry.window && entry.window.closed) {
            newMap.set(id, { ...entry, active: false });
            handleChildClosed(id); // 触发关闭处理
          }
        });
        return newMap;
      });
    };

    const interval = setInterval(checkWindows, 1000);
    return () => clearInterval(interval);
  }, [windowMap]);

  return (
    <div>
      <h3>多子窗口通信演示</h3>
      <Button type="primary" onClick={openNewTab}>
        打开新的子标签页
      </Button>
      
      <div style={{ marginTop: 20 }}>
        <h4>已打开的子窗口列表</h4>
        <List
          itemLayout="horizontal"
          dataSource={windowList}
          renderItem={(item) => (
            <List.Item>
              <List.Item.Meta
                title={`窗口 ID: ${item.id}`}
                description={`状态: ${item.status}\n创建时间: ${item.created.toLocaleString()}`}
              />
              <Button 
                size="small" 
                onClick={() => sendToWindow(item.id, 'refreshData')}
                disabled={item.status !== '活跃'}
              >
                发送命令
              </Button>
              <Tag color={
                item.status === '活跃' ? 'success' : 
                item.status === '初始化中' ? 'processing' : 'default'
              }>
                {item.status}
              </Tag>
            </List.Item>
          )}
        />
      </div>
    </div>
  );
};
export default OpenMultipleCommunicatingTabs;
